import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken, parseToken } from '@/utils/auth'

// 初始化用户信息
const initUserInfo = () => {
  const token = getToken()
  if (token) {
    const tokenInfo = parseToken(token)
    if (tokenInfo) {
      // 角色映射：将中文角色转换为英文
      const roleMapping = {
        '管理员': 'ADMIN',
        '教师': 'TEACHER', 
        '学生': 'STUDENT'
      }
      
      // 处理角色映射，支持中文和英文
      let mappedRole = tokenInfo.role
      if (roleMapping[tokenInfo.role]) {
        mappedRole = roleMapping[tokenInfo.role]
      } else if (['ADMIN', 'TEACHER', 'STUDENT'].includes(tokenInfo.role)) {
        mappedRole = tokenInfo.role // 已经是英文，直接使用
      }
      
      return {
        username: tokenInfo.username,
        realName: tokenInfo.realName || tokenInfo.username,
        role: mappedRole,
        relatedId: tokenInfo.relatedId
      }
    }
  }
  return null
}

const state = {
  token: getToken(),
  userInfo: initUserInfo(),
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    console.log('SET_TOKEN mutation被调用:', token)
    console.log('设置前的state.token:', state.token)
    state.token = token
    console.log('设置后的state.token:', state.token)
    console.log('state对象:', state)
  },
  SET_USER_INFO: (state, userInfo) => {
    console.log('SET_USER_INFO mutation被调用:', userInfo)
    console.log('设置前的state.userInfo:', state.userInfo)
    state.userInfo = userInfo
    console.log('设置后的state.userInfo:', state.userInfo)
    console.log('state对象:', state)
  },
  SET_ROLES: (state, roles) => {
    console.log('SET_ROLES mutation被调用:', roles)
    state.roles = roles
  }
}

const actions = {
  // 用户登录
  login({ commit }, loginForm) {
    const { username, password } = loginForm
    return new Promise((resolve, reject) => {
      login({ username, password }).then(response => {
        console.log('Store收到登录响应:', response)
        const { data } = response
        console.log('提取的data:', data)
        
        // 保存token
        console.log('保存token:', data.token)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        
        // 保存用户信息
        // 角色映射：将中文角色转换为英文
        const roleMapping = {
          '管理员': 'ADMIN',
          '教师': 'TEACHER', 
          '学生': 'STUDENT'
        }
        
        // 处理角色映射，支持中文和英文
        let mappedRole = data.role
        if (roleMapping[data.role]) {
          mappedRole = roleMapping[data.role]
        } else if (['ADMIN', 'TEACHER', 'STUDENT'].includes(data.role)) {
          mappedRole = data.role // 已经是英文，直接使用
        }
        
        const userInfo = {
          username: data.username,
          realName: data.realName,
          role: mappedRole, // 映射角色
          relatedId: data.relatedId
        }
        console.log('保存用户信息:', userInfo)
        console.log('原始角色:', data.role, '映射后角色:', userInfo.role)
        commit('SET_USER_INFO', userInfo)
        
        // 返回完整的响应数据，包括message
        resolve(response)
      }).catch(error => {
        console.error('Store登录失败:', error)
        reject(error)
      })
    })
  },

  // 获取用户信息
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 从token中获取用户名
      const tokenInfo = parseToken(state.token)
      if (!tokenInfo || !tokenInfo.username) {
        reject('Token无效，请重新登录')
        return
      }
      
      getUserInfo(tokenInfo.username).then(response => {
        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录')
          return
        }
        
        // 角色映射：将中文角色转换为英文
        const roleMapping = {
          '管理员': 'ADMIN',
          '教师': 'TEACHER', 
          '学生': 'STUDENT'
        }
        
        // 处理角色映射，支持中文和英文
        let mappedRole = data.role
        if (roleMapping[data.role]) {
          mappedRole = roleMapping[data.role]
        } else if (['ADMIN', 'TEACHER', 'STUDENT'].includes(data.role)) {
          mappedRole = data.role // 已经是英文，直接使用
        }
        
        // 后端直接返回User对象，但需要映射角色
        const userInfo = {
          ...data,
          role: mappedRole // 使用映射后的角色
        }
        
        console.log('getUserInfo - 原始角色:', data.role, '映射后角色:', mappedRole)
        console.log('getUserInfo - 用户信息:', userInfo)
        
        commit('SET_USER_INFO', userInfo)
        commit('SET_ROLES', [mappedRole]) // 将映射后的角色包装成数组
        resolve({ userInfo, roles: [mappedRole] })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER_INFO', null)
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 重置状态
  resetState({ commit }) {
    commit('SET_TOKEN', '')
    commit('SET_USER_INFO', null)
    commit('SET_ROLES', [])
    removeToken()
  }
}

const getters = {
  token: state => {
    console.log('token getter被调用，state.token:', state.token)
    return state.token
  },
  userInfo: state => {
    console.log('userInfo getter被调用，state.userInfo:', state.userInfo)
    return state.userInfo
  },
  userRole: state => state.userInfo?.role || '',
  userName: state => state.userInfo?.realName || '',
  roles: state => state.roles,
  isLoggedIn: state => !!state.token
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
